/**
 * 用户状态管理
 * 职责：用户登录、登出、信息管理
 */
import { defineStore } from "pinia"
import { computed, ref } from "vue"
import { getUserInfo as apiGetUserInfo, login as apiLogin, logout as apiLogout } from "@/api/modules/user"
import { recordLoginDevice } from "@/api/modules/device"
import { getDeviceFingerprint } from "@/utils/business/device"
import { ElMessage } from "element-plus"
import { secureStorage } from "@/utils/core/storage"
import router from "@/router"

export const useUsersStore = defineStore("user", () => {
  // 状态
  const token = ref(secureStorage.getItem("token"));
  const userInfo = ref(secureStorage.getItem("userInfo"));
  const loading = ref(false);

  // 计算属性
  const isLoggedIn = computed(() => !!token.value);
  const isAdmin = computed(() => userInfo.value?.role === "ADMIN");

  // 获取用户信息
  async function getUserInfo() {
    if (!token.value) return false;

    try {
      loading.value = true;
      const response = await apiGetUserInfo();
      if (response && response.data) {
        userInfo.value = response.data;
        secureStorage.setItem("userInfo", response.data);
        return true;
      }
      return false;
    } catch (error) {
      return false;
    } finally {
      loading.value = false;
    }
  }

  // 用户登录
  async function login(loginData) {
    try {
      loading.value = true;
      const response = await apiLogin(loginData);

      if (response && response.data && response.data.token) {
        const loginResult = response.data;
        token.value = loginResult.token;
        const { token: userToken, ...userData } = loginResult;
        userInfo.value = userData;

        secureStorage.setItem("token", loginResult.token);
        secureStorage.setItem("userInfo", userData);

        // 异步记录登录信息，不阻塞登录流程
        recordDeviceInfo(userData.id, loginResult.token).catch(err => {
          console.warn("记录登录设备失败:", err);
        });

        ElMessage.success("登录成功");

        const redirect = router.currentRoute.value.query.redirect || "/";
        router.push(redirect);

        return true;
      } else {
        ElMessage.error("登录失败，无效的响应数据");
        return false;
      }
    } catch (error) {
      return false;
    } finally {
      loading.value = false;
    }
  }

  // 记录登录设备信息
  async function recordDeviceInfo(userId, sessionToken) {
    try {
      const deviceInfo = await getDeviceFingerprint();
      await recordLoginDevice({
        userId,
        deviceId: deviceInfo.deviceId,
        deviceName: deviceInfo.deviceName,
        deviceType: deviceInfo.deviceType,
        browser: deviceInfo.browser,
        os: deviceInfo.os,
        loginMethod: "PASSWORD",
        ipAddress: deviceInfo.ipAddress || "unknown",
        location: deviceInfo.location || "",
        sessionToken
      });
    } catch (error) {
      console.error("记录设备信息失败:", error);
      // 不抛出错误，避免影响登录流程
    }
  }

  // 用户登出
  async function logout() {
    try {
      if (token.value) {
        await apiLogout();
      }
    } catch (error) {
      // 忽略登出API错误
    } finally {
      token.value = null;
      userInfo.value = null;
      secureStorage.removeItem("token");
      secureStorage.removeItem("userInfo");
      router.push("/login");
    }
  }

  return {
    token,
    userInfo,
    loading,
    isLoggedIn,
    isAdmin,
    getUserInfo,
    login,
    logout,
  };
});
